package com.free4inno.pagesite.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Author: ZhaoHaotian.
 * Date: 2022/1/26.
 * 使用 okhttp3 进行 http 请求
 */

@Slf4j
@Component
public class HttpUtils {

    public String getRequest(String url) throws Exception {
        log.info("getRequest ---- start ----");
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        try {
            Response response = client.newCall(request).execute();
            if (response.code() == 200) {
                String jsonData = response.body().string();
                log.info("getRequest ---- end ---- 成功");
                return jsonData;
            } else {
                log.info("getRequest ---- end ---- 失败");
                throw new Exception("getRequest failed!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("getRequest ---- end ---- 异常");
            throw new Exception("getRequest error!");
        }
    }

    public String postRequest(String url, String jsonBody) throws Exception {
        log.info("postRequest ---- start ----");
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, jsonBody.toString());
        Request request = new Request.Builder().url(url).post(body).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.code() == 200) {
                String jsonData = response.body().string();
                log.info("postRequest ---- end ---- 成功");
                return jsonData;
            } else {
                log.info("postRequest ---- end ---- 失败");
                throw new Exception("getRequest failed!");
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("postRequest ---- end ---- 异常");
            throw new Exception("getRequest error!");
        }
    }
}
